package structure

// 样本比较器
type SampleCompare[T comparable] struct {
	Group     any
	SampleLen int
	Sample    []T
}

// 初始化比较器
func (info *SampleCompare[T]) Init(group any, sampleLen int) {
	info.Group = group
	info.SampleLen = sampleLen
	info.Sample = make([]T, 0, info.SampleLen)
}

// 增加一个样本 group不同时,会重置比较器
func (info *SampleCompare[T]) SampleAdd(group any, value T) {
	if info.Group != group {
		info.Init(group, info.SampleLen)
	}

	info.Sample = append(info.Sample, value)
	if len(info.Sample) > info.SampleLen {
		info.Sample = info.Sample[len(info.Sample)-info.SampleLen:]
	}
}

// 获取比较结果
// 只有当所有样本通过比较函数得到的结果都为True时,才判定满足条件
// 样本数量不足时 || 缺乏比较函数时 当作不满足条件处理
func (info *SampleCompare[T]) Result(compare func(T) bool) bool {
	// 缺乏比较函数 || 样本不足
	if compare == nil || len(info.Sample) == 0 || len(info.Sample) != info.SampleLen {
		return false
	}

	for _, v := range info.Sample {
		if !compare(v) {
			return false
		}
	}

	return true
}
